import type { ReactNode } from 'react';
import type { ExtendedRouteObject } from './index';

export interface MenuItem {
  key: string;
  label: string;
  icon?: ReactNode;
  path: string;
}

/**
 * 从路由配置中提取菜单项
 * @param routes 路由配置
 * @returns 菜单项数组
 */
export function getMenuItemsFromRoutes(routes: ExtendedRouteObject[]): MenuItem[] {
  const menuItems: MenuItem[] = [];
  let index = 0;

  function traverseRoutes(routeList: ExtendedRouteObject[], parentPath = '') {
    routeList.forEach((route) => {
      // 跳过没有 path 或 meta 的路由，以及隐藏的路由
      if (!route.path || !route.meta || route.meta.hidden) {
        // 如果有子路由，继续遍历
        if (route.children) {
          traverseRoutes(route.children, parentPath);
        }
        return;
      }

      // 构建完整路径
      const fullPath = parentPath + route.path;
      const normalizedPath = fullPath.replace(/\/+/g, '/'); // 处理多个斜杠

      // 添加菜单项
      menuItems.push({
        key: String(++index),
        label: route.meta.label,
        icon: route.meta.icon,
        path: normalizedPath === '' ? '/' : normalizedPath,
      });

      // 递归处理子路由
      if (route.children) {
        traverseRoutes(route.children, normalizedPath);
      }
    });
  }

  traverseRoutes(routes);
  return menuItems;
}
